package com.z.sys.service.impl;

import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.z.sys.entity.EmailConfig;
import com.z.sys.mapper.EmailConfigMapper;
import com.z.sys.service.IEmailConfigService;
import com.z.sys.vo.EmailVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * 消息通知Service业务层处理
 *
 * @author z
 * @date 2022-12-09
 */
@Service
public class EmailConfigServiceImpl extends ServiceImpl<EmailConfigMapper, EmailConfig> implements IEmailConfigService {


    @Override
    public boolean send(EmailVo emailVo, File file) throws Exception {
        EmailConfig emailConfig =  this.list().get(0);
        if(emailConfig.getId() == null){
            throw new Exception("请先配置，再操作");
        }
        // 封装
        MailAccount account = new MailAccount();
        // 设置用户
        String user = emailConfig.getFromUser().split("@")[0];
        account.setUser(user);
        account.setHost(emailConfig.getHost());
        account.setPort(Integer.parseInt(emailConfig.getPort()));
        account.setAuth(true);
        try {
            // 对称解密
            SymmetricCrypto des = new SymmetricCrypto(SymmetricAlgorithm.DES, "zxy123qweasd".getBytes());
            account.setPass(des.decryptStr(emailConfig.getPass()));
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        account.setFrom((StringUtils.isEmpty(emailConfig.getUser())? user : emailConfig.getUser())+"<"+emailConfig.getFromUser()+">");
        // ssl方式发送
        account.setSslEnable(true);
        // 使用STARTTLS安全连接
        account.setStarttlsEnable(true);
        String content = emailVo.getContent();
        // 设置邮件发送超时时间
        account.setConnectionTimeout(500000); // 连接超时时间，单位毫秒
        account.setTimeout(500000);
        // account.setSocketTimeout(500000);

        // 发送
        try {
            int size = emailVo.getTos().size();
            Mail mail = Mail.create(account);
            mail.setTos(emailVo.getTos().toArray(new String[size]))
                    .setTitle(emailVo.getSubject())
                    .setContent(content)
                    .setHtml(true)
                    //关闭session
                    .setUseGlobalSession(false);
            if(file.exists()) {
                mail.setFiles(new File[]{
                        file
                });
            }

            mail.send();
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
